package gw.com.android.ui.onlive.analyst;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;

import www.com.library.view.XRecyclerView;

/**
 * @author jett
 * @since 2018-07-19.
 */
public class AnalystRecyclerView extends XRecyclerView {

    private ViewGroup rootView;

    public AnalystRecyclerView(Context context) {
        super(context);
    }

    public AnalystRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AnalystRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    int lastY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastY = (int) ev.getRawY();
                if (isScrollTop()) {
                    getAnalystRoot().requestDisallowInterceptTouchEvent(false);
                } else {
                    getAnalystRoot().requestDisallowInterceptTouchEvent(true);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int dy = (int) (ev.getRawY() - lastY);
                lastY = (int) ev.getRawY();
                if (dy > 0) {
                    if (isScrollTop()) {
                        getAnalystRoot().requestDisallowInterceptTouchEvent(false);
                    } else {
                        getAnalystRoot().requestDisallowInterceptTouchEvent(true);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isScrollTop() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();
        int position = layoutManager.findFirstCompletelyVisibleItemPosition();
        return position == 0;
    }

    private ViewGroup getAnalystRoot() {
        if (rootView != null) {
            return rootView;
        }
        rootView = (ViewGroup) getParent();
        while (rootView != null && !(rootView instanceof AnalystRootView)) {
            rootView = (ViewGroup) rootView.getParent();
        }
        return rootView;
    }

}
